<template>
  <div class="database-config-container">
    <h1>数据库配置管理</h1>

    <el-button 
      type="primary" 
      @click="refreshData"
      :loading="sharedStore.loading"
    >
      刷新数据
    </el-button>

    <el-table 
      :data="processedData"
      v-loading="sharedStore.loading"
      style="width: 100%; margin-top: 20px"
    >
      <!-- 类型列 -->
      <el-table-column prop="type" label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="row.type === 'local' ? 'primary' : 'success'">
            {{ row.type === 'local' ? '本地' : '远程' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- IP地址列 -->
      <el-table-column label="IP地址" width="150">
        <template #default="{ row }">
          <el-input 
            v-if="row.editing"
            v-model="row.editInfo.IP"
            size="small"
          />
          <span v-else>{{ row.info.IP }}</span>
        </template>
      </el-table-column>

      <!-- 端口列 -->
      <el-table-column label="端口" width="100">
        <template #default="{ row }">
          <el-input 
            v-if="row.editing"
            v-model="row.editInfo.port"
            size="small"
          />
          <span v-else>{{ row.info.port }}</span>
        </template>
      </el-table-column>

      <!-- 账户列 -->
      <el-table-column label="账户" width="120">
        <template #default="{ row }">
          <el-input 
            v-if="row.editing"
            v-model="row.editInfo.username"
            size="small"
          />
          <span v-else>{{ row.info.username }}</span>
        </template>
      </el-table-column>

      <!-- 密码列 -->
      <el-table-column label="密码" width="150">
        <template #default="{ row }">
          <el-input 
            v-if="row.editing"
            v-model="row.editInfo.password"
            type="text"
            size="small"
          />
          <span v-else>{{ row.info.password }}</span>
        </template>
      </el-table-column>

<!-- Org ID 列修改为只显示 -->
<el-table-column label="Org ID" width="150">
        <template #default="{ row }">
          <span>{{ row.info.orgId || '-' }}</span>
        </template>
      </el-table-column>

      



      <!-- Token列 -->
      <el-table-column label="Token">
        <template #default="{ row }">
          <el-tooltip effect="dark" :content="row.info.token" placement="top">
            <span class="truncate-text">{{ truncate(row.info.token) }}</span>
          </el-tooltip>
          <el-button 
            type="text" 
            @click="copyText(row.info.token)"
            icon="el-icon-copy"
          />
        </template>
      </el-table-column>

     <!-- Buckets 列修改为直接显示 -->
     <el-table-column label="Buckets" width="250">
        <template #default="{ row }">
          <div class="bucket-list">
            <template v-if="row.info.buckets.length">
              <div 
                v-for="bucket in row.info.buckets" 
                :key="bucket.id"
                class="bucket-item"
              >
                <span class="bucket-id">{{ bucket.id }}:</span>
                <span class="bucket-name">{{ bucket.name }}</span>
              </div>
            </template>
            <span v-else>-</span>
          </div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button
              v-if="!row.editing"
              type="primary"
              size="small"
              @click="startEdit(row)"
            >
              编辑
            </el-button>
            <template v-else>
              <el-button
                type="success"
                size="small"
                @click="saveConfig(row)"
              >
                保存
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="cancelEdit(row)"
              >
                取消
              </el-button>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useSharedStore } from '@/stores/useSharedStore'
import { ElMessage } from 'element-plus'

type ProcessedItem = {
  id: string
  type: 'local' | 'remote'
  info: any
  editing: boolean
  editInfo: any
}

const sharedStore = useSharedStore()

const processedData = computed<ProcessedItem[]>(() => {
  return sharedStore.influxdbInfos.map(item => ({
    id: item.id,
    type: item.type,
    info: item.info || createEmptyInfo(),
    editing: false,
    editInfo: { ...(item.info || createEmptyInfo()) }
  }))
})

// 创建空配置
const createEmptyInfo = () => ({
  IP: '',
  port: '',
  orgId: '',
  token: '',
  cookies: '',
  username: '',
  password: '',
  buckets: []
})

// 刷新数据
function refreshData() {
  sharedStore.get_config_info()
}

// 开始编辑
function startEdit(row: ProcessedItem) {
  row.editing = true
  row.editInfo = { ...row.info }
}

// 取消编辑
function cancelEdit(row: ProcessedItem) {
  row.editing = false
}

// 保存配置
async function saveConfig(row: ProcessedItem) {
  try {
    await sharedStore.update_config(row.id, row.editInfo)
    Object.assign(row.info, row.editInfo)
    row.editing = false
    ElMessage.success('配置更新成功')
  } catch (error) {
    ElMessage.error('配置更新失败')
  }
}

// 截断长文本
function truncate(text: string, length = 20) {
  return text?.length > length ? text.substring(0, length) + '...' : text || ''
}

// 复制文本
function copyText(text: string) {
  navigator.clipboard.writeText(text)
  ElMessage.success('复制成功')
}
</script>

<style scoped>
.truncate-text {
  display: inline-block;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}

.database-config-container {
  padding: 20px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
}

.el-table :deep(.el-table__cell) {
  padding: 8px 0;
}
</style>
